$(function () {
	//动态添加报名表单
    var strText = '<div class="form-group row">';
	strText += '   <label class="col-sm-12 control-label">';
	strText += '       <i id="close1" style="font-style: normal;text-align: right;float: right;width: 20px; height: 20px; background-color: gainsboro;color: white;text-align: center;line-height: 20px;position: absolute;right: 0px;top: -16px;">X</i> </label>';
	strText += ' </div>';
	strText += '<div class="form-group row">';
    strText += '<label class="col-sm-4 control-label">';
    strText += '<i style="color: red;">*</i> &nbsp;姓名</label>';
    strText += '<div class="col-sm-8">';
    strText += '     <input type="text" class="form-control nameP" placeholder="请输入姓名">';
    strText += '   </div>';
    strText += ' </div>';
    strText += ' <div class="form-group row">';
    strText += '   <label class="col-sm-4 control-label">';
    strText += '       <i style="color: red;">*</i> &nbsp;电话</label>';
    strText += '  <div class="col-sm-8">';
    strText += '  <input type="text" class="form-control phoneP"  placeholder="请输入手机号码">';
    strText += '   </div>';
    strText += ' </div>';
    strText += ' <div class="form-group row">';
    strText += ' <label class="col-sm-4 control-label">';
    strText += '    <i style="color: red;">*</i> &nbsp;门店地址</label>';
    strText += '   <div class="col-sm-8 pca">';
    strText += '   <div class="col-sm-12" style="padding: 0px;">';
    strText += '     <select class="form-control provinceP">';
    strText += '         <option>请选择省份</option>';
    strText += '      </select>';

    strText += '   </div>';
    strText += '    <div class="col-sm-12" style="padding: 0px;">';
    strText += '   <select class="form-control cityP">';
    strText += '     <option>请选择城市</option>';
    strText += '  </select>';
    strText += ' </div>';
    strText += ' <div class="col-sm-12" style="padding: 0px;">';
    strText += '   <select class="form-control typeP" style="display: none;">';
    strText += '      <option>民用</option>';
    strText += '      <option>办公</option>';
    strText += '  </select>';
    strText += '  </div>';
    strText += ' <div class="col-sm-12" style="padding: 0px;">';
    strText += '    <select class="form-control shopP">';
    strText += '      <option>请选择门店</option>';
    strText += '   </select>';
    strText += '</div>';
    strText += ' </div>';
    strText += '</div>';
    strText += '<div class="form-group btnfooter" style="text-align: right;    margin-bottom: 0px;">';
    strText += '<div  class="btn btn-primary btn-lg btn-block" style="margin: 0px;background-color: red;border: none !important; border-radius: 22px;" id="ModalSubmitP">';
    strText += '    确认报名';
    strText += ' </div>';
    strText += '</div>';
	strText += '  <div class="form-group row" style="text-align: center; margin-bottom: 0px;">';
	strText += '    <b class="bText bText1"></b>';
	strText += '    <b class="bNumber"></b>';
	strText += '    <b class="bText bText2"></b>';
	strText += '  </div>';

	$("#formFix").append(strText);
	var btext1 = $("#formFix").attr('bText1');
	var btext2 = $("#formFix").attr('bText2');
	var bNumber = $("#formFix").attr('bNumber');
	$("b.bText1").html(btext1);
	$("b.bText2").html(btext2);
	$("b.bNumber").html(bNumber);
	
	var randomNumber = parseInt(Math.random()*15);
	var  newNumber;
	if(localStorage.getItem('bNumber')){
		var getLocalNUmber = localStorage.getItem('bNumber');
		 newNumber = parseInt(randomNumber) + parseInt(getLocalNUmber);
		
	}else{
		 newNumber= parseInt(randomNumber)+parseInt(bNumber);
		
	}
	$("b.bNumber").html(newNumber);
	
	
	$("#close1").bind("click",function(){
		$("#formFix").hide();
	})
	 
	
	
    var simulationData = [{
        name: "广州省",
        data: offlineData
    }]
    var localProvince = [];
    var localArr = [];
    var arr_province = []; //省
    var arr_city = []; //市区
    var currentSelectProvince; //当前选择的省
    var currentSelectCity; //当前选择的市
    var isSignUpSuccess = false; //是否报名成功

    simulationData.forEach(function (item, index) {
        localProvince[item.name] = item.data;
        localProvince[item.name].forEach(function (item) {
            localArr[item.name + item.city] = item.shop_info;
        })
    })
    //默认加载省份
    for (var i = 0; i < simulationData.length; i++) { //下拉栏内的元素来源于数组中的元素，遍历数组
        var option = new Option(simulationData[i].name, simulationData[i].name); //创建Option对象（这个O要大写），存入值
        if ($("select.province")) {
            //province.appendChild(option); //把option添加到event对象的末尾
            //$("select.province").empty();
            $("select.province").append(option);
        }
        if ($("select.provinceP")) {
            $("select.provinceP").append(option);
        }


    }
    //绑定省份事件
    $("select.province").bind("change", function () {
        var val = $(this).children('option:selected').val();
        var getType = $("select.type option:selected").val()

        if (localProvince[val]) {
            var city = [];
            localProvince[val].forEach(function (item, index) {
                city.push(item);
            })
            $("select.city").empty();
            $("select.shop").empty();
            //console.log(city)
            city.forEach(function (item2, index2) {
                var option = new Option(item2.city, item2.city); //创建Option对象（这个O要大写），存入值	
                $("select.city").append(option);
                //console.log(item2)
                //console.log(index2)
                item2.shop_info.forEach(function (item3, index3) {
                    if (item3.type == getType) {
                        var option2 = new Option(item3.title, item3.title); //创建Option对象（这个O要大写），存入值	
                        $("select.shop").append(option2);
                    }
                })
            })
        }
    })
    $("select.provinceP").bind("change", function () {
        var val = $(this).children('option:selected').val();
        var getType = $("select.typeP option:selected").val()

        if (localProvince[val]) {
            var city = [];
            localProvince[val].forEach(function (item, index) {
                city.push(item);
            })
            $("select.cityP").empty();
            $("select.shopP").empty();
            city.forEach(function (item2, index2) {
                var option = new Option(item2.city, item2.city); //创建Option对象（这个O要大写），存入值	
                $("select.cityP").append(option);

                item2.shop_info.forEach(function (item3, index3) {
                    if (item3.type == getType) {
                        var option2 = new Option(item3.title, item3.title); //创建Option对象（这个O要大写），存入值	
                        $("select.shopP").append(option2);
                    }
                })
            })
        }
    })

    //绑定城市事件
    $("select.city").bind("change", function () {
        var getType = $("select.type option:selected").val();
        var val = $("select.province").children('option:selected').val();
        var cityText = $(this).children('option:selected').val();

        if (localProvince[val]) {
            var city = [];
            localProvince[val].forEach(function (item, index) {
                city.push(item);
            })
            //$("select.city").empty();
            $("select.shop").empty();
            city.forEach(function (item2, index2) {
                //console.log(item2.city);
                if (cityText == item2.city) {

                    item2.shop_info.forEach(function (item3, index3) {
                        if (item3.type == getType) {
                            var option2 = new Option(item3.title, item3.title); //创建Option对象（这个O要大写），存入值	
                            $("select.shop").append(option2);
                        }
                    })
                }
            })
        }
    })
    $("select.cityP").bind("change", function () {
        var getType = $("select.typeP option:selected").val();
        var val = $("select.provinceP").children('option:selected').val();
        var cityText = $(this).children('option:selected').val();

        if (localProvince[val]) {
            var city = [];
            localProvince[val].forEach(function (item, index) {
                city.push(item);
            })
            //$("select.city").empty();
            $("select.shopP").empty();
            city.forEach(function (item2, index2) {
                //console.log(item2.city);
                if (cityText == item2.city) {

                    item2.shop_info.forEach(function (item3, index3) {
                        if (item3.type == getType) {
                            var option2 = new Option(item3.title, item3.title); //创建Option对象（这个O要大写），存入值	
                            $("select.shopP").append(option2);
                        }
                    })
                }

            })
        }

    })

    //绑定类型事件
    $("select.type").bind("change", function () {
        var val = $("select.province").children('option:selected').val();
        var getType = $("select.type option:selected").val()
        //       		//console.log(localProvince[val]);
        //			//console.log(getType);
        if (localProvince[val]) {
            var city = [];
            localProvince[val].forEach(function (item, index) {
                city.push(item);
            })
            $("select.city").empty();
            $("select.shop").empty();
            city.forEach(function (item2, index2) {
                var option = new Option(item2.city, item2.city); //创建Option对象（这个O要大写），存入值	
                $("select.city").append(option);
                item2.shop_info.forEach(function (item3, index3) {
                    if (item3.type == getType) {
                        var option2 = new Option(item3.title, item3.title); //创建Option对象（这个O要大写），存入值	
                        $("select.shop").append(option2);
                    }
                })
            })
        }
    })
    $("select.typeP").bind("change", function () {
        var val = $("select.provinceP").children('option:selected').val();
        var getType = $("select.typeP option:selected").val()

        if (localProvince[val]) {
            var city = [];
            localProvince[val].forEach(function (item, index) {
                city.push(item);
            })
            $("select.cityP").empty();
            $("select.shopP").empty();
            city.forEach(function (item2, index2) {
                var option = new Option(item2.city, item2.city); //创建Option对象（这个O要大写），存入值	
                $("select.cityP").append(option);
                item2.shop_info.forEach(function (item3, index3) {
                    if (item3.type == getType) {
                        var option2 = new Option(item3.title, item3.title); //创建Option对象（这个O要大写），存入值	
                        $("select.shopP").append(option2);
                    }
                })
            })
        }
    })

    //获取页面传值
    function GetRequest() {
        var url = location.search; //获取url中"?"符后的字串   
        var theRequest = new Object();
        if (url.indexOf("?") != -1) {
            var str = url.substr(1);
            strs = str.split("&");
            for (var i = 0; i < strs.length; i++) {
                theRequest[strs[i].split("=")[0]] = unescape(strs[i].split("=")[1]);
            }
        }
        return theRequest;
    }

    //点击模态框取消按钮
    $(".modal-footer .btn-default").bind("click", function () {
        $("#myModal").hide(500);
        $(".modal-backdrop").hide(500)

    })

    //点击模态框右上角关闭按钮
    $("#myModal .close").bind("click", function () {
        $("#myModal").hide(500);
        $(".modal-backdrop").hide(500);
        $("#contentModalMap").hide();
        $("#contentModalSignUp").show();
    })
    $("#myModal .backPage").bind("click", function () {
        $("#myModal").hide(500);
        $(".modal-backdrop").hide(500);
        $("#contentModalMap").hide();
        $("#contentModalSignUp").show();
    })

    //实时监听手机号码输入
    $(".phoneP").bind("keyup paste input change", function () {
        var val = $(this).val();
        $(this).val(val.replace(/\D|^0/g, ''));
    })
    //实时监听手机号码输入
    $(".phone").bind("keyup paste input change", function () {
        var val = $(this).val();
        $(this).val(val.replace(/\D|^0/g, ''));
    })



    //点击确认报名
    $("#ModalSubmit").bind("click", function () {
        var getPro = GetRequest(); //获取页面传值
        var recordSource = "无";
        var name = $("input.name").val();
        var phone = $("input.phone").val();
        var province = $("select.province option:selected").val();
        var city = $("select.city option:selected").val();
        var shop = $("select.shop option:selected").val();
        var myreg =
            /^(((13[0-9]{1})|(14[0-9]{1})|(17[0]{1})|(15[0-3]{1})|(15[5-9]{1})|(18[0-9]{1}))+\d{8})$/;
        if (name == '') {
            alert('请输入姓名！');
            return false;
        } else if (phone == "") {
            alert('请输入手机号码！');
            return false;
        } else if (!myreg.test(phone)) {
            alert('手机号码不正确！');
            return false;
        } else if (province == '') {
            alert('请选择省份!');
            return false;
        } else if (city == "") {
            alert('请选择城市!');
            return false;
        } else if (shop == "") {
            alert('请选择门店!');
            return false;
        }
        if (getPro.formCode) {
            recordSource = getPro.formCode;
        }
        var options = {
            cmd: 'addSubmit',
            formId: 1,
            submitContentList: JSON.stringify([{
                "id": 0,
                "type": 0,
                "must": true,
                "val": $("input.name").val()
            }, {
                "id": 1,
                "type": 8,
                "must": true,
                "val": $("input.phone").val()
            }, {
                "id": 2,
                "type": 11,
                "must": true,
                "val": $("select.province option:selected").val() + $(
                        "select.city option:selected")
                    .val() + $("select.shop option:selected").val()
            }, {
                "id": 3,
                "type": 0,
                "must": true,
                "val": recordSource
            }]),
            vCodeId: 3471,
            validateCode: '',
            tmpFileList: []
        }
        $.ajax({
            type: "post",
            url: "/ajax/siteForm_h.jsp",
            data: options,
            async: true,
            success: function (res) {
                //  alert('报名成功!')
                //$("#myModal").hide(500);
                //$(".modal-backdrop").hide(500);
                var shopName = $("select.shop option:selected").val();
                var selectItm = {};
                var params = '';
                offlineData.forEach(function (item, index) {
                    if (item.shop_info) {
                        item.shop_info.forEach(function (item2, index2) {
                            if (item2.title == shopName) {
                                //console.log(item2)
                                selectItm = item2;
                                selectItm.city = $(
                                    "select.city option:selected").val();
                                params = item2.address + ',' + item2.title +
                                    ',' +
                                    item2.tel;
                            }
                        })
                    }
                })
                var option2 = {
                    mobile: $("input.phone").val(),
                    key: 3211,
                    params: params
                }
                console.log(option2);

                //报名成功之后进行消息发送

                $.ajax({
                    type: "get",
                    url: "http://api.kinhom.com/sms/sendsms",
                    data: option2,
                    async: true,
                    dataType: "jsonp",
                    success: function (res) {
                        //console.log(res)
                        alert('报名成功!');
                        $("#formFix").hide();
                        isSignUpSuccess = true;
                        generateMap(selectItm);
                        //报名成功之后进行消息发送


                    },
                    error: function (err) {
                        //console.log(err);
                    },
                    complete: function (res) {
                        //console.log(res)
                        alert('报名成功!');
                        isSignUpSuccess = true;
                        $("#formFix").hide();

                        generateMap(selectItm);
                    }
                });

            }
        });
        //console.log(options);
    })
    $("#ModalSubmitP").bind("click", function () {
        var getPro = GetRequest(); //获取页面传值
        var recordSource = "无";
        var name = $("input.nameP").val();
        var phone = $("input.phoneP").val();
        var province = $("select.provinceP option:selected").val();
        var city = $("select.cityP option:selected").val();
        var shop = $("select.shopP option:selected").val();
        var myreg =
            /^(((13[0-9]{1})|(14[0-9]{1})|(17[0]{1})|(15[0-3]{1})|(15[5-9]{1})|(18[0-9]{1}))+\d{8})$/;
        if (name == '') {
            alert('请输入姓名！');
            return false;
        } else if (phone == "") {
            alert('请输入手机号码！');
            return false;
        } else if (!myreg.test(phone)) {
            alert('手机号码不正确！');
            return false;
        } else if (province == '') {
            alert('请选择省份!');
            return false;
        } else if (city == "") {
            alert('请选择城市!');
            return false;
        } else if (shop == "") {
            alert('请选择门店!');
            return false;
        }
        if (getPro.formCode) {
            recordSource = getPro.formCode;
        }
        var options = {
            cmd: 'addSubmit',
            formId: 1,
            submitContentList: JSON.stringify([{
                "id": 0,
                "type": 0,
                "must": true,
                "val": $("input.nameP").val()
            }, {
                "id": 1,
                "type": 8,
                "must": true,
                "val": $("input.phoneP").val()
            }, {
                "id": 2,
                "type": 11,
                "must": true,
                "val": $("select.provinceP option:selected").val() + $(
                        "select.cityP option:selected")
                    .val() + $("select.shopP option:selected").val()
            }, {
                "id": 3,
                "type": 0,
                "must": true,
                "val": recordSource
            }]),
            vCodeId: 3471,
            validateCode: '',
            tmpFileList: []
        }
        $.ajax({
            type: "post",
            url: "/ajax/siteForm_h.jsp",
            data: options,
            async: true,
            success: function (res) {

                var shopName = $("select.shopP option:selected").val();
                var selectItm = {};
                var params = '';
                offlineData.forEach(function (item, index) {
                    //console.log(item)
                    if (item.shop_info) {
                        item.shop_info.forEach(function (item2, index2) {
                            //console.log(item2.title)

                            if (item2.title == shopName) {
                                selectItm = item2;
                                selectItm.city = $(
                                    "select.cityP option:selected").val();
                                params = item2.address + ',' + item2.title +
                                    ',' +
                                    item2.tel;
                            }
                        })
                    }
                })
                //console.log(shopName);
                var option2 = {
                    mobile: $("input.phoneP").val(),
                    key: 3211,
                    params: encodeURI(params)
                }
                //报名成功之后进行消息发送
                $.ajax({
                    type: "get",
                    url: "http://api.kinhom.com/sms/sendsms",
                    data: option2,
                    async: true,
                    success: function (res) {
                        alert('报名成功!');
                        isSignUpSuccess = true;
                        $("#formFix").hide();

                        generateMap(selectItm);
                    },
                    error: function (err) {
                        //console.log(err);
                    },
                    complete: function (res) {
                        //console.log(res)
                        alert('报名成功!');
                        isSignUpSuccess = true;
                        $("#formFix").hide();

                        generateMap(selectItm);
                    }
                });

                //             $("#myModal").hide(500);
                //             $(".modal-backdrop").hide(500);
            }
        });
        //console.log(options);
    })

    //点击页面上参与链接的标签
    $("a").bind("click", function () {
        var aHtml = $(this).html();
		console.log(aHtml);
        if (aHtml != '参与活动') {
            return false;
        }
        if (!isSignUpSuccess) {
            $("#myModal").show(500);
            $(".modal-backdrop").show(500);
            $("#contentModalMap").hide();
            $("#contentModalSignUp").show();
        } else {
            alert("你已经成功报名!")
        }

        return false;
    })
    //页面加载的时候,进行判断是否需要生成计时器
    var ad_time = $(".ad_time");
    loalInt = [];
    if (ad_time) {
        $(".ad_time").each(function (index, item) {
            var type = $(".ad_time").eq(index).attr('type');
            if (type == 1 || type == '1') {
                var str =
                    '<p class="activity">活动剩余时间<span class="d">00</span>天<span class="h">00</span>时<span class="m">00</span>分<span class="s">00</span>秒</p>'
                //					str += '<p class="activityEndTime">结束时间:2018/7/19</p>'
//                 str += '<div class="price">'
//                 str += '<p class="p1">活动价<i class="activity_Price">368</i>元</p>'
//                 str += '<p class="p2">市场价<i class="market_Price">7360</i>元</p>'
//                 str += '</div>'
                str += '<div class="inactivities">参与活动</div>'
                $(".ad_time").eq(index).append(str);
            }
            var $inactivities = $(".ad_time").eq(index).find('.inactivities');
            $inactivities.bind("click", function () {
                $("#contentModalMap").hide();
                $("#contentModalSignUp").show();
                $("#myModal").show(500);
                $(".modal-backdrop").show(500);

            })

            var aIn = 'ad_time' + (index + 1)
            loalInt[aIn] = setInterval(function () {
                var b = ad_time + (index + 1);
                var activityEndTime = $(".ad_time").eq(index).attr('activityEndTime');
                //$(".ad_time").eq(index).find('.activityEndTime').html('活动结束时间:' + activityEndTime);
                var EndTime = new Date(activityEndTime);
                var NowTime = new Date();
                var t = EndTime.getTime() - NowTime.getTime();
                var d = 0;
                var h = 0;
                var m = 0;
                var s = 0;
                if (t >= 0) {
                    d = Math.floor(t / 1000 / 60 / 60 / 24);
                    h = Math.floor(t / 1000 / 60 / 60 % 24);
                    m = Math.floor(t / 1000 / 60 % 60);
                    s = Math.floor(t / 1000 % 60);
                    $(".ad_time").eq(index).find('.d').html(d);
                    $(".ad_time").eq(index).find('.h').html(h);
                    $(".ad_time").eq(index).find('.m').html(m);
                    $(".ad_time").eq(index).find('.s').html(s);
                } else {
                    $(".ad_time").eq(index).hide();
                    clearInterval(loalInt[aIn]);
                }

            }, 1000);

            //	//console.log(index);
        })
    }

    function lxfEndtime() {
        $t = $('#t').html();
        if ($t != 0) {
            $('#t').html($t - 1);
            $i = setTimeout("lxfEndtime()", 1000);
        } else {
            $('#t').html(6000);
            clearTimeout($i);
        }
    };

    function GetDateStr(num, str) {
        var today = new Date();
        var nowTime = today.getTime();
        var ms = 24 * 3600 * 1000 * num;
        today.setTime(parseInt(nowTime + ms));
        var oYear = today.getFullYear();
        var oMoth = (today.getMonth() + 1).toString();
        if (oMoth.length <= 1) oMoth = '0' + oMoth;
        var oDay = today.getDate().toString();
        if (oDay.length <= 1) oDay = '0' + oDay;
        return oYear + str + oMoth + str + oDay;
    }

    function GetRTime(n) {
        var EndTime = new Date(GetDateStr(n, '/'));
        var NowTime = new Date();
        var t = EndTime.getTime() - NowTime.getTime();
        var d = 0;
        var h = 0;
        var m = 0;
        var s = 0;
        if (t >= 0) {
            d = Math.floor(t / 1000 / 60 / 60 / 24);
            h = Math.floor(t / 1000 / 60 / 60 % 24);
            m = Math.floor(t / 1000 / 60 % 60);
            s = Math.floor(t / 1000 % 60);
        } else {
            if (n == 1) {
                window.clearInterval(aIn);
            } else if (n == 2) {
                window.clearInterval(aIn2);

            } else if (n == 3) {
                window.clearInterval(aIn3);
            }

        }
        if (n == 1) {
            $('.t_d').html(d);
            $('.t_h').html(h);
            $('.t_m').html(m);
            $('.t_s').html(s);
            $('.t_d').html(d);
        } else if (n == 2) {
            $('.t_d2').html(d);
            $('.t_h2').html(h);
            $('.t_m2').html(m);
            $('.t_s2').html(s);
            $('.t_d2').html(d);

        } else if (n == 3) {
            $('.t_d3').html(d);
            $('.t_h3').html(h);
            $('.t_m3').html(m);
            $('.t_s3').html(s);
            $('.t_d3').html(d);
        }

    }

    //实时更新地图模态框的状态
    function generateMap(item) {
        //console.log("捡来啊")
        $("#myModal").show(500);
        $(".modal-backdrop").show(500);
        $("#contentModalMap").show();
        $("#contentModalSignUp").hide();

        var city = item.city;
        var position = item.position;
        var address = item.address;
        var service_time = item.service_time;
        var tel = item.tel;
        var title = item.title;
        var type = item.type;
        $("#ShopMessage  .shopName").html('门店 :  &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;' + title);
        $("#ShopMessage .shopAddress").html('地址 :&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; ' + address);

        $("#ShopMessage .shopPhone").html('电话 : &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;' + tel);

        $("#ShopMessage .shopServiceTime").html('营业时间 : ' + service_time);
        if (ishasMap) {

            var map = new AMap.Map('containerMap2', {
                resizeEnable: true,
                center: [position[0], position[1]],
                zoom: 13
            });
            var marker = new AMap.Marker({
                map: map,
                icon: '',
                position: [position[0], position[1]],
                offset: new AMap.Pixel(-12, -36)
            });
            marker.setTitle(title);
            marker.setLabel({
                //label默认蓝框白底左上角显示，样式className为：amap-marker-label
                offset: new AMap.Pixel(20, 20), //修改label相对于maker的位置
                content: title
            });
        }

    }
    var positionCenter = [113.422060021, 22.5451775145];
    var ishasMap = document.getElementById("containerMap2");
    var items = {
        "city": "广州市",
        "position": [113.286432, 23.092007],
        "title": "海珠店",
        "type": "办公",
        "address": "江南大道南411号香江家居四楼",
        "tel": "020-84472503",
        "service_time": "9:30-20:30（周一-周日）"

    }
	$(".modal-backdrop").hide();

   // generateMap(items);

})
